//日志
const {
    logger
} = require('../config/logger');

//引入数据库连接池
const pool = require('../config/mysql');
//引入数据库语句
const noticeQuery = require('../db/noticeQuery/noticeQuery');

//解析token
const {
    token_verify
} = require('../config/jwt')

//引入时间模块
const sd = require('silly-datetime');

//定义在线用户
let hashName = new Map();

//引入租赁聊天
const {
    auditNotice
} = require('./auditNotice');

function initNotice(io) {
    io.on('connection', function (socket) {
        logger().info(`用户: ${socket.id}进入了小程序`);
        //开启通知功能
        socket.on('openNotice', function (data) {
            const token = data.token;
            const {
                userId
            } = token_verify(token);
            hashName.set(userId, socket.id); // 储存上线的用户
            //初始化未读消息
            pool.query(noticeQuery.select_sysMess, userId, (error, result) => {
                if (error) {
                    logger().error("获取未读消息失败: " + error);
                    return;
                } else {
                    const data = JSON.parse(JSON.stringify(result));
                    if (hashName.has(userId)) {
                        const toSocket = hashName.get(userId);
                        io.to(toSocket).emit('system_message', data)
                    }
                }
            });
        });
        //开启系统通知消息
        auditNotice(io, hashName);
        // 当关闭连接后触发 disconnect 事件
        socket.on('disconnect', function () {
            logger().info(`用户: ${socket.id}离开了小程序`);
        });
    });
}

module.exports = initNotice;